/**
 * @author William
 * 2012-3-5
 */
package com.ytu.clouddis.google;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.LevelListDrawable;
import android.widget.ListView;

import com.google.api.client.apache.ApacheHttpTransport;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.googleapis.auth.clientlogin.ClientLogin;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.util.DateTime;
import com.google.api.client.xml.atom.AtomContent;
import com.google.api.client.xml.atom.AtomParser;
import com.ytu.clouddisk.clientlogin.LoginUtil;
import com.ytu.clouddisk.face.BrowserActivity;
import com.ytu.clouddisk.face.FileExplorer;
import com.ytu.clouddisk.face.LVAdapter;
import com.ytu.clouddisk.face.ListViewItemData;
import com.ytu.clouddisk.face.R;
import com.ytu.clouddisk.face.Varibles;
import com.ytu.clouddisk.gmodels.DocsEntry;
import com.ytu.clouddisk.gmodels.DocsFeed;
import com.ytu.clouddisk.gmodels.DocsUrl;
import com.ytu.clouddisk.gmodels.Util;

public class DocsControl {

	private static DocsControl instance;
	private Context mContext;
	private static List<DocsEntry> docs = new ArrayList<DocsEntry>();
	private static HttpTransport transport;
	private String postLink;
	private SharedPreferences pref = null;
	private static GoogleHeaders headers = null;
	private static DocsFeed docsFeed = null;

	public static DocsControl getInstance(Context m) {
		instance = new DocsControl(m);
		return instance;
	}
	
	/**
	 * 初始化所有Docs请求的头部内容，并加入token
	 * @param c
	 */
	private DocsControl(Context c) {
		mContext = c;
		HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
		transport = GoogleTransport.create();
		headers = (GoogleHeaders) transport.defaultHeaders;
		headers.setApplicationName("CloudBackup");
		headers.gdataVersion = "3.0";
	    pref = c.getSharedPreferences("accounts", Context.MODE_PRIVATE);
//		headers.setGoogleLogin(pref.getString(CloudBackupActivity.DOCS_TOKEN,
//				null));
	    
	    String token = pref.getString(Varibles.GOOGLE_TOKEN +"User", null);
		headers.authorization = GoogleHeaders.getGoogleLoginValue(token);
		
		AtomParser parser = new AtomParser();
		parser.namespaceDictionary = Util.NAMESPACE_DICTIONARY;
		transport.addParser(parser);
	}

	// public DocsControl(){
	// HttpTransport transport = new HttpTransport();
	// transport.addParser(AuthKeyValueParser.INSTANCE);
	// HttpRequest request = transport.buildPostRequest();
	// request.setUrl("https://docs.google.com/feeds/default/private/full");
	// UrlEncodedContent content = new UrlEncodedContent();
	//
	// content.data = this;
	// request.disableContentLogging = true;
	// request.content = content;
	// return request.execute().parseAs(Response.class);
	// }

	/*
	 * private void authenticatedLogin(String authToken) { this.authToken =
	 * authToken; ((GoogleHeaders))
	 * transport.defaultHeaders.setGoogleLogin(authToken); authenticated(); }
	 */

	/**
	 * 获取所有文件夹
	 * @param filter
	 * @return
	 */
	public List<DocsEntry> getDocsRoot(boolean filter) {
		List<DocsEntry> doc = new ArrayList<DocsEntry>();
		try {
			DocsUrl url;
			if (filter) {
				url = DocsUrl
						.fromRelativePath("/feeds/default/private/full/folder%3Aroot/contents/-/folder");
			} else {
				url = DocsUrl.fromRelativePath("/feeds/default/private/full");
			}
			while (true) {
				DocsFeed userFeed = docsFeed = DocsFeed.executeGet(transport,
						url);
				this.postLink = userFeed.getPostLink();
				if (userFeed.docs != null) {
					doc.addAll(userFeed.docs);
				}
				String nextLink = userFeed.getNextLink();
				if (nextLink == null) {
					break;
				}
			}
			return doc;
		} catch (Exception e) {
			e.printStackTrace();
		}
return null;
	}

	@SuppressWarnings({ "null" })
	public void executeRefreshDocs() {

		List<String> DocsNames = new ArrayList<String>();
		this.docs = getDocsRoot(false);
		int numDocs = docs.size();
		for (int i = 0; i < numDocs; i++) {
			DocsNames.add(docs.get(i).title.toString());
		}
		LevelListDrawable levelListDrawable = (LevelListDrawable) mContext
				.getResources().getDrawable(R.drawable.listview_image_file); // 获取图片列表
		ListViewItemData mListViewItemData = new ListViewItemData(
				levelListDrawable, DocsNames, DocsNames.size());

		ListView mListView = BrowserActivity.getListView();
		LVAdapter mListViewAdapter = new LVAdapter(mContext, mListViewItemData);
		mListView.setAdapter(mListViewAdapter);
	}

	public static void uploadFile(String path) {
		// 弹出Docs文件列表对话框
		File file = new File(path);
		try {
			HttpRequest request = transport.buildPostRequest();
			request.url = DocsUrl
					.fromRelativePath("/feeds/default/private/full");
			headers.setSlugFromFileName(file.getName());
			request.headers = headers;
			// 定义Content
			InputStreamContent content = new InputStreamContent(); // 用的是流
			content.inputStream = new FileInputStream(file);
			content.type = "text/plain";
			content.length = file.length();
			request.content = content;
			request.execute().ignore();

			// success = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}

	}

	//
	// @Override
	// protected void onListItemClick(ListView l, View v, int pos, long id) {
	//
	// }

	// 新建文件夹
	public void createFolder() {

		DocsEntry folders = new DocsEntry();
		folders.access = "private";
		folders.title = "New Folder" + new DateTime(new Date());

		HttpRequest request = transport.buildPostRequest();
		request.url = DocsUrl.fromRelativePath("/feeds/default/private/full");

		request.headers = headers;
		// InputStreamContent content = new InputStreamContent(); //用的是流

		try {
			AtomContent content = new AtomContent();
			content.namespaceDictionary = Util.NAMESPACE_DICTIONARY;
			content.entry = folders;

			request.content = content;
			request.execute().ignore();
		} catch (IOException e) {
			e.printStackTrace();
		}// .parseAs();
		executeRefreshDocs();
		// downloadFile();
	}

	// 下载，还原
	public static void downloadFile() {

	}
}
